layui.use(['layer', 'form'], function() {
	var layer = layui.layer,
		form = layui.form;

	var url_local = "navdata.json";
	//这里可以是一个远程文件 比如https://www.daervin.com/navdata.json
	var url_default = "navdata.json";
	var url;


	console.log("加载设置...");
	// 加载设置
	var defaultConfig = {
		url: '',
		ver: "1.2.1"
	};
	// 默认配置
	chrome.storage.sync.get(defaultConfig, function(items) {
		url = items.url;
		if (typeof url == "undefined" || url == null || url == "") {
			url = url_default;
			console.log("加载设置失败，重置为url_default...");
		}
		console.log(url);
		normalProcess();
	});

	//渲染方法
	function render(data) {
		console.log(data);
		var version = data.version;
		var navData = data.nav;
		if (defaultConfig.ver != version) {
			// 设置一个醒目的标签
			chrome.browserAction.setBadgeText({
				text: 'new'
			});
			chrome.browserAction.setBadgeBackgroundColor({
				color: [255, 0, 0, 255]
			});
			$('#version').html("当前版本V" + defaultConfig.ver + ", 可更新版本V" + version);
		} else {
			chrome.browserAction.setBadgeText({
				text: ''
			});
			$('#version').html('V' + defaultConfig.ver);
		}
		console.log('执行到渲染方法...');
		$.each(navData, function(i, info) {
			// 第一层级
			var title = info.title;
			var navs = info.data;
			var html = '<fieldset class="layui-elem-field" style="padding:5px;"><legend>' + title +
				'</legend><div class="nav">';
			$.each(navs, function(j, nav) {
				var special = nav.special != null && nav.special != undefined && nav.special;
				if (i == 0) {
					if (special) {
						html += '<a href="#" class="layui-btn layui-btn-danger layui-btn-sm" style="margin-left:10px;" url="' +
							nav.url + '" title="' + nav.tips + '">' + nav.title + '</a>';
					} else {
						html += '<a href="#" class="layui-btn layui-btn-normal layui-btn-sm" style="margin-left:10px;" url="' +
							nav.url + '" title="' + nav.tips + '">' + nav.title + '</a>';
					}
				} else {
					if (special) {
						html += '<a href="#" class="layui-btn layui-btn-danger layui-btn-sm" style="margin-left:10px;" url="' + nav
							.url +
							'" title="' + nav.tips + '">' + nav.title + '</a>';
					} else {
						html += '<a href="#" class="layui-btn layui-btn-sm" style="margin-left:10px;" url="' + nav.url +
							'" title="' + nav.tips + '">' + nav.title + '</a>';
					}
				}
			});
			html += '</div></fieldset>';
			$('#box').append(html);
		});
		console.log('渲染方法结束...');
	}

	function normalProcess() {
		console.log("执行到normalProcess...");
		if (url == url_local) {
			$('#dataFrom').html('localhost');
		} else {
			$('#dataFrom').html(url);
		}
		console.log("渲染数据来源结束...");
		$.getJSON(url, function(data) {
			console.log("从url中getJSON...");
			render(data);
			//获取自定义导航
			diyProcess();
		}).error(function() {
			console.log("从url中getJSON出错...");
			$.getJSON(url_local, function(data) {
				console.log("再次从url_local中getJSON...");
				$('#dataFrom').html('localhost');
				render(data);
				//获取自定义导航
				diyProcess();
			});
		});

		console.log("监听指定开关...");
		//监听指定开关
		form.on('switch(diy-setting-switch)', function(data) {
			$('#diy-setting').toggle(100);
			$('#diyNavBox i').toggle(100);
		});

	}

	//自定义导航处理流程
	function diyProcess() {
		console.log("获取自定义导航...");
		var diyNavs = [];
		var cc = '';
		var lastIndex = 0;
		chrome.storage.sync.get({
			diy_navs_info: '[]'
		}, function(items) {
			cc = items.diy_navs_info;
			console.log(cc);
			diyNavs = JSON.parse(items.diy_navs_info);
			//自定义导航渲染
			console.log("自定义导航渲染...");
			$.each(diyNavs, function(i, nav) {
				lastIndex = nav.id;
				$('#diyNavBox').append('<a href="#" class="layui-btn layui-btn-sm" style="margin-left:10px;" url="' + nav.url +
					'">' +
					nav.title + '</a>' + '<i class="layui-icon" data-id="' + nav.id + '">&#xe64d;</i>');
			});
			bindDelDiyNav(diyNavs);
		});

		// 设置自定义导航
		console.log("给设置自定义导航绑定click...");
		$('#save').on('click', function() {
			var title = $('#title').val();
			var url = $('#url').val();
			lastIndex++;
			var diyNav = {
				"id": lastIndex,
				"title": title,
				"url": url
			};
			if (title == "" || url == "") {
				layer.msg('请输入标题和链接！');
				return;
			}
			diyNavs.push(diyNav);
			chrome.storage.sync.set({
				diy_navs_info: JSON.stringify(diyNavs)
			}, function() {
				console.log('设置自定义成功！');
				layer.msg('设置自定义成功！');
				$('#diyNavBox').append('<a href="#" class="layui-btn layui-btn-sm" style="margin-left:10px;" url="' + url +
					'">' +
					title + '</a>' + '<i class="layui-icon"  style="display: inline;" data-id="' + lastIndex + '">&#xe64d;</i>'
				);
				bindDelDiyNav(diyNavs);
			});
			$('#title').val('');
			$('#url').val('');
		});
	}

	//删除自定义导航
	function bindDelDiyNav(diyNavs) {
		console.log('进入删除自定义导航！');
		console.log('给数据源导航绑定click');
		$('.nav a').click(function() {
			chrome.tabs.create({
				url: $(this).attr('url')
			});
		});
		console.log('给自定义导航绑定click');
		$('#diyNavBox i').on('click', function() {
			var diyNavsTmp = [];
			var id = $(this).attr('data-id');
			$.each(diyNavs, function(i, nav) {
				if (nav.id != id) {
					diyNavsTmp.push(nav);
				}
			});
			diyNavs = diyNavsTmp;
			chrome.storage.sync.set({
				diy_navs_info: JSON.stringify(diyNavs)
			});
			$(this).prev('a').remove();
			$(this).remove();
			console.log(JSON.stringify(diyNavs));
			layer.msg('删除自定义成功！');
		});
	}

});
